package com.dhnsoft.shortLink.admin.config;

import com.dhnsoft.shortLink.admin.common.biz.user.UserFlowRiskControlFilter;
import com.dhnsoft.shortLink.admin.common.biz.user.UserTransmitFilter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.StringRedisTemplate;

/**
 * 用户配置自动装配
 */
@Configuration
public class UserConfiguration {

    /**
     * 用户信息传递过滤器
     */
    @Bean
    public FilterRegistrationBean<UserTransmitFilter> globalUserTransmitFilter(StringRedisTemplate stringRedisTemplate) {
        FilterRegistrationBean<UserTransmitFilter> registration = new FilterRegistrationBean<>();
        //创建一个 UserTransmitFilter 过滤器的实例，并将 stringRedisTemplate 作为参数传递给它。这样做是为了在过滤器中使用 Redis 进行用户信息的获取。
        registration.setFilter(new UserTransmitFilter(stringRedisTemplate));
        //指定了该过滤器所拦截的 URL 模式，这里表示拦截所有的 URL 请求。
        registration.addUrlPatterns("/*");
        //设置过滤器的顺序，数字越小表示优先级越高，这里设置为 0 表示最高优先级。
        registration.setOrder(0);
        return registration;
    }

    /**
     * 用户操作流量风控过滤器
     */
    @Bean
    @ConditionalOnProperty(name = "short-link.flow-limit.enable", havingValue = "true")
    public FilterRegistrationBean<UserFlowRiskControlFilter> globalUserFlowRiskControlFilter(
            StringRedisTemplate stringRedisTemplate,
            UserFlowRiskControlConfiguration userFlowRiskControlConfiguration) {
        FilterRegistrationBean<UserFlowRiskControlFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new UserFlowRiskControlFilter(stringRedisTemplate, userFlowRiskControlConfiguration));
        registration.addUrlPatterns("/*");
        registration.setOrder(10);
        return registration;
    }
}
